#!/usr/bin/python
#-*- coding=utf-8 -*-

from __future__ import division
import re
import time
import sys, getopt
import commands
import os
import zmq
import json
import socket
import fcntl
import struct

net_path = "/proc/net/dev"
cpu_path = "/proc/stat"
mem_path = "/proc/meminfo"
eth_name = "eno1"
zmq_server = "tcp://minik.leyecloud.com:5558"
monitor_time = 300

def get_ip_address(ifname):
	s = socket.socket(socket.AF_INET, socket.SOCK_DGRAM)
	return socket.inet_ntoa(fcntl.ioctl(
				s.fileno(),
				0x8915, # SIOCGIFADDR
				struct.pack('256s', ifname[:15])
				)[20:24])


def getBandWidth(eth='eth0'):
	fp = open(net_path)
	datas = fp.read()
	fp.close()
	patten = eth + ".*"
	if not re.search(patten, datas):
		print "The %s don't exist %s" %(net_path, eth)
		return None
	result = re.search(patten, datas).group().replace(':', ' ').split()
	band_dict = dict()
	band_dict['receive'] = int(result[1]) * 8 / 1024 / 1024
	band_dict['send'] = int(result[9]) * 8 / 1024 / 1024
	return band_dict

def getCpuInfo():
	fp = open(cpu_path)
	datas = fp.readlines()
	fp.close()
	for data in datas:
		data = data.strip()
		columns = data.split()
		if len(columns) < 5:
			continue
		if columns[0].startswith('cpu'):
			break
	cpu_dict = dict()
	cpu_dict['total'] = 0
	for i in xrange(1, len(columns)):
		cpu_dict['total'] += long(columns[i])
	cpu_dict['idle'] = long(columns[4])
	return cpu_dict

def getMemInfo(status = False):
	if(not status):
		fp = open(mem_path)
		datas = fp.readlines()
		fp.close()
		temp = dict()
		for data in datas:
			data = data.lower().replace(':', ' ').split()
			temp[data[0]] = long(data[1])
		memused = temp['memtotal'] - temp['memfree'] - temp['buffers'] - temp['cached'] - temp['shmem'] 
		return {'memtotal': round(temp['memtotal'] / 1024 , 2), 'memused': round(memused / 1024 , 2), 'percent': round(memused * 100  / temp['memtotal'], 2) }

	cmd = "free | sed '1d' | awk '{print $1, $2, $3}'"
	status,output = commands.getstatusoutput(cmd)
	if status != 0:
		return None
	else:
		output = output.replace(":", ' ')
		output = output.split('\n')
		mem_dict = dict()
		for i in xrange(len(output)):
			temp = output[i].split()
			if temp[0].lower() == 'mem' or temp[0].lower() == 'swap':
				mem_dict["%stotal" %temp[0].lower()] = long(temp[1])
				mem_dict['%sused'  %temp[0].lower()] = long(temp[2])
		return mem_dict

def conn_info():
	cmd = "netstat -n | awk '/^tcp/ {++S[$NF]} END {for(a in S) print a, S[a]}'"
	status, output = commands.getstatusoutput(cmd)
	if status != 0:
		return None
	output = output.split('\n')
	result = dict()
	for data in output:
		temp = data.split()
		result[temp[0]] = temp[1]
	return result
	
		

def disk_stat(path = None):
	if(path != None):
		hd = dict()
		disk = os.statvfs('/var/www/html/old_resource')
		total = round(disk.f_bsize * disk.f_blocks / 1024 / 1024 / 1024 / 1024, 2)
		free = round(disk.f_bsize * disk.f_bfree / 1024 / 1024 / 1024 / 1024, 2)
		return {'total': total, 'free': free, 'used': total - free, 'percent': round((total - free) * 100 / total, 2)}
	cmd = "df -h | sed '1d' | awk '{print $2,$3,$4,$5,$6}'"
	status,output = commands.getstatusoutput(cmd)
	if(status != 0):
		return None
	output = output.split('\n')
	result = dict()
	for i in xrange(len(output)):
		temp = output[i].split()
		result[temp[4]] = {'total': temp[0], 'used': temp[1], 'free':temp[2], 'percent': temp[3]}
	return result

def main():
	context = zmq.Context()
	socket = context.socket(zmq.PUSH)
	socket.connect(zmq_server)
	sysInfo_dict = dict()
	try:
		while True:
			sysInfo_dict.clear()
			band_old = getBandWidth(eth_name)
			cpu_old = getCpuInfo()
			time.sleep(monitor_time)
			band_new = getBandWidth(eth_name)
			cpu_new = getCpuInfo()
			band = dict()
			band['receive'] = round((band_new['receive'] - band_old['receive']) / monitor_time, 2)
			band['send'] = round((band_new['send'] - band_old['send']) / monitor_time, 2)
			total = cpu_old['total'] - cpu_new['total']
			idle = cpu_old['idle'] - cpu_new['idle']
			cpu = round(100 - idle * 100 / total, 2)
			sysInfo_dict['band'] = band
			sysInfo_dict['cpu'] = '%g%%' %cpu
			sysInfo_dict['memInfo'] = getMemInfo()
			sysInfo_dict['disk'] = 	disk_stat()
			sysInfo_dict['hostip'] = get_ip_address(eth_name)
			sysInfo_dict['time_token'] = time.time()
			sysInfo_dict['conn_info'] = conn_info()
			#info_json = json.dumps(sysInfo_dict)
			print sysInfo_dict 
			socket.send_json(sysInfo_dict)
	except Exception, e:
		print e
		socket.close()
		context.term()
		
if __name__ == '__main__':
	main()
